<?php
/**
* @package care_api
*/
/**
*/

require_once($root_path.'include/care_api_classes/class_core.php');
/**
*  Person methods. 
*
* Note this class should be instantiated only after a "$db" adodb  connector object  has been established by an adodb instance
* @author Astrid Paravisini
* @author Aixbel Martinez
* @version beta 2.0.1
* @package care_api
*/
class Interconsulta extends Core {
	/**#@+
	* @access private
	*/
	/**
	* Table name for interconsulta
	* @var string
	*/
        var $tb_interconsulta='care_interconsulta_interconsulta';
	/**
	* Table names for foreign keys
	* @var string
	*/
        var $tb_preg_resp='care_interconsulta_preguntas_respuestas';

	var $tb_person='care_person';
	
	var $tb_adjunto='care_interconsulta_adjuntos';

	var $tb_users='care_users';
	
	var $tb_especialidad='care_interconsulta_especialidad';
	
	var $tb_paciente='care_interconsulta_paciente';

        var $tb_datos_paciente='care_interconsulta_datos_paciente';

        var $tb_grupo='care_interconsulta_grupo_triaje';

        var $tb_espeusuario='care_interconsulta_usuarioPerteneceEspecialidad';

        var $tb_bitacora='care_interconsulta_bitacora';

	/**
	* SQL query
	*/
	var $sql;
	/**#@-*/
	/**
	* PID number
	* @var int
	*/
	var $id;
	/**
	* Sql query result buffer
	* @var adodb record object
	*/
	var $result;
	/**
	* Universal flag
	* @var boolean
	*/
	var $ok;
	/**
	* Internal data buffer
	* @var array
	*/
	var $data_array;
	/**
	* Internal data buffer 2
	* @var array
	*/
	var $data2_array;
	/**
	* Universal buffer
	* @var mixed
	*/
	var $buffer;
	/**
	* Returned row buffer
	* @var array
	*/
	var $row;
	/**
	* Returned interconsulta data buffer
	* @var array
	*/
	var $interconsulta=array();
        /**
	* Returned person data buffer
	* @var array
	*/
	var $person=array();
	/**
	* Preloaded data flag
	* @var boolean
	*/
	var $is_preloaded=false;
	/**
	* Valid number flag
	* @var boolean,
	* @var array
	*/
	var $basic_list='id,id_paciente, id_especialidad, fecha_hora_consulta, establecimiento, motivo, justificacion, enfermedad_actual, examen_fisico, peso, talla, presion_arterial, temp, respiratoria, pulso, login_consultante, login_consultado, fecha_hora_respuesta, respuesta, diagnostico, tratamiento, observaciones, IDx, pauta_terapeutica, id_datos_paciente, comentarios, comentarios_resp, estado, motivo_cierre, clasificacion, interconsultas_previas,traslado,noadherencia,comentarios_clasif, name_first, name_2, name_middle, name_last, sex, ethnic_orig, create_id';

	/**
	* Field names of table care_person
	* @var array
	*/
	var  $elems_array=array(
				'id',
				 'id_paciente',
				 'id_especialidad',
				 'establecimiento',
                                 'fecha_hora_consulta',
                                 'motivo',
				 'justificacion',
                                 'enfermedad_actual',
				 'examen_fisico',
				 'peso',
				 'talla',
				 'presion_arterial',
				 'temp',
				 'respiratoria',
				 'pulso',
				 'login_consultante',
				 'login_consultado',
                                 'fecha_hora_respuesta',
				 'respuesta',
                                 'diagnostico',
                                 'tratamiento',
                                 'observaciones',
				 'IDx',
				 'pauta_terapeutica',
				 'id_datosPaciente',
                                 'comentarios',
                                 'comentarios_resp',
                                 'estado',
                                 'motivo_cierre',
				'clasificacion',
				'interconsultas_previas',
				'traslado',
				'noadherencia',
				'comentarios_clasif');
	var  $elems2_array=array('id',
				'apellido_1',
				'apellido_2',
				'name_1',
				'name_2',
				'sex',
				'etnia');
	/**
	* Constructor
	* @param int ID number
	*/
	function Interconsulta ($id='') {
	       $this->id=$id;
	       $this->ref_array=$this->elems_array;
	       $this->coretable=$this->tb_interconsulta;
	}
	/**
	* Sets the ID number.
	* @access public
	* @param int ID number
	*/
	function setID($id) {
	    $this->id=$id;
	}
	
	/**
	* Prepares the internal buffer array for insertion routine.
	* @access private
	*/
	function prepInsertArray(){
            global $_POST;
		$x='';
		$v='';
		$this->data_array=NULL;
		$this->data2_array=NULL;

		while(list($x,$v)=each($this->elems_array)) {
	    	if(isset($_POST[$v])&&!empty($_POST[$v])) $this->data_array[$v]=$_POST[$v];
	    }
		while(list($x,$v)=each($this->elems2_array)) {
	    	if(isset($_POST[$v])&&!empty($_POST[$v])) $this->data2_array[$v]=$_POST[$v];
	    }

    }	
	/**
	* Inserts the data into the care_person table.
	* @access private
	* @param int PID number
	* @return boolean
	*/
   /* function insertDataFromArray() {
		global $db;
		$array =$this->data_array;
		$array2 =$this->data2_array;
		$x='';
		$v='';
		$index='';
		$values='';

		if(is_array($array)){

			if(is_array($array2)){ //Inserto los datos del paciente de la interconsulta
				while(list($x,$v)=each($array2)) {
					$index.="$x,";
					$values.="'$v',";
				}
				$index=substr_replace($index,'',(strlen($index))-1);
				$values=substr_replace($values,'',(strlen($values))-1);
		
				//$this->sql="INSERT INTO $this->tb_datos_paciente ($index) VALUES ($values)";
                                //var_dump($array2);
                                //var_dump($this->tb_datos_paciente);
                                //var_dump($this->sql);

                                //$a=$this->Transact();
                                $a = $db->Transact("",$array2,"Insert",$this->tb_datos_paciente);

				if($a){
					/*$this->sql=" SELECT LAST_INSERT_ID()";
					if($this->result=$db->Execute($this->sql)) {
						if($this->result->RecordCount()) {
							$res= $this->result->FetchRow();
							$id_datos = $res['LAST_INSERT_ID()'];
						}
					}*/
                                       /* $salida=$db->LastInserted();
                                        if($salida){
                                            $id_datos = $salida;
                                        }

				}
                                else{
                                        return false;
                                }
			}

			$x='';
			$v='';
			$index='';
			$values='';
			if($id_datos){
				$index.='id_datos_paciente, ';
				$values.="'$id_datos', ";
			}

			while(list($x,$v)=each($array)) {
				$index.="$x,";
				$values.="'$v',";
			} 
			$index=substr_replace($index,'',(strlen($index))-1);
			$values=substr_replace($values,'',(strlen($values))-1);
	
			//$this->sql="INSERT INTO $this->tb_interconsulta ($index) VALUES ($values)";
                        //var_dump($array);
                        //var_dump($this->tb_interconsulta);
                        //var_dump($this->sql);



			// 			echo $this->sql;
			//$b = $this->Transact();
                        $b = $db->Transact("",$array,"Insert",$this->tb_interconsulta);

                        if($b){
                            /*$this->sql="SELECT LAST_INSERT_ID()";
                            if($this->result=$db->Execute($this->sql)) {
                                if($this->result->RecordCount()) {
                                    $res= $this->result->FetchRow();
                                    $this->id = $res['LAST_INSERT_ID()'];
                                }
                            }*/
                         //   $salida=$db->LastInserted();
                       /*                 if($salida){
                                            $this->id = $salida;
                                        }

                        }
                        else{
                            return false;
                        }

		}else{
			return false;
		}

		return true;
	}*/
    function insertDataFromArray() {
		global $db;
		$array =$this->data_array;
		$array2 =$this->data2_array;
		$x='';
		$v='';
		$index='';
		$values='';

		if(is_array($array)){

			if(is_array($array2)){ //Inserto los datos del paciente de la interconsulta
				while(list($x,$v)=each($array2)) {
					$index.="$x,";
					$values.="'$v',";
					$values1[].=$v;
						
				}


				$index=substr_replace($index,'',(strlen($index))-1);
				$values=substr_replace($values,'',(strlen($values))-1);
				//var_dump( $values1);

				$value= array('apellido_1'=>$values1[0], 'apellido_2'=>$values1[1],'name_1'=>$values1[2],'name_2'=>$values1[3],'sex'=>$values1[4], 'etnia'=>$values1[5]);

				//$this->sql="INSERT INTO $this->tb_datos_paciente ($index) VALUES ($values)";
				//echo $this->sql;
				//$a=$this->Transact();
             		
					$db->Transact("",$value,"Insert",$this->tb_datos_paciente);
			    
				if($db){
					/*$this->sql=" SELECT LAST_INSERT_ID()";
					if($this->result=$db->Execute($this->sql)) {
						if($this->result->RecordCount()) {
							$res= $this->result->FetchRow();
							$id_datos = $res['LAST_INSERT_ID()'];
						}
					}*/
					$salida = $db->SelectProcedureResult('LAST_INSERT_ID()');
					if($salida) {
						$id_datos= $salida[0]['LAST_INSERT_ID()'];
					} 
				}
			}

			$x='';
			$v='';
			$index='';
			$values='';
			$values1='';
			$value='';
			if($id_datos){
				$index.='id_datos_paciente, ';
				$values.="'$id_datos', ";
			}

			while(list($x,$v)=each($array)) {
				$index.="$x,";
				$values.="'$v',";
				$values1[].=$v;
			} 
			$index=substr_replace($index,'',(strlen($index))-1);
			$values=substr_replace($values,'',(strlen($values))-1);
			//var_dump( $values);
			//var_dump($id_datos);
			$value= array('id_paciente'=>$values1[0], 'id_especialidad'=>$values1[1],'establecimiento'=>$values1[2],'fecha_hora_consulta'=>$values1[3],'presion_arterial'=>$values1[4], 'temp'=>$values1[5], 'respiratoria'=>$values1[6], 'pulso'=>$values1[7], 'login_consultante'=>$values1[8],'id_datos_paciente'=>$id_datos, 'comentarios'=>$values1[9], 'interconsultas_previas'=>$values1[10]);

			$db->Transact("",$value,"Insert",$this->tb_interconsulta);

			//$this->sql="INSERT INTO $this->tb_interconsulta ($index) VALUES ($values)";
			//echo $this->sql;
			//$b = $this->Transact();

                        if($db){
                            /*$this->sql="SELECT LAST_INSERT_ID()";
                            if($this->result=$db->Execute($this->sql)) {
                                if($this->result->RecordCount()) {
                                    $res= $this->result->FetchRow();
                                    $this->id = $res['LAST_INSERT_ID()'];
                                }
                            }*/
                            $salida = $db->SelectProcedureResult('LAST_INSERT_ID()');
							if($salida) {
								$this->id= $salida[0]['LAST_INSERT_ID()'];
							}
                        }

		}else{
			return false;
		}

		return true;
	}




	/**
	* Inserts the data from the internal buffer array into the care_person table.
	*
	* The data must be packed in the buffer array with index keys as outlined in the <var>$elems_array</var> array.
	* @access public
	* @return boolean
	*/
	function insertDataFromInternalArray() {
            global $_POST;
	    //$this->data_array=NULL;
		$this->prepInsertArray();
		return $this->insertDataFromArray();
	}


	function updateDataFromInternalArray($idInter) {
		global $_POST;

                $this->id = $idInter;
		$this->prepInsertArray();
		return $this->updateDataFromArray($this->data_array,$idInter);
	}


    function updateDataFromArray(&$array,$item_nr='') {
		global $db;
		/*$x='';
		$v='';
		$sql='';*/
		
		if(!is_array($array)) return false;
		if(empty($item_nr)||!is_numeric($item_nr)) return false;
		/*while(list($x,$v)=each($array)) {
			if(stristr($v,'concat')||stristr($v,'null')) $sql.="$x= $v,";
		    	else $sql.="$x='$v',";
		}
		$sql=substr_replace($sql,'',(strlen($sql))-1);*/
		//var_dump($array);
    	    
        //$this->sql="UPDATE $this->tb_interconsulta SET $sql WHERE id=$item_nr";
		//echo $this->sql;
		return $db->Transact(array('id'=>$item_nr),$array,'Update',$this->tb_interconsulta);
		
	}


      function getValueBy($login_ico, $id_esp = '', $st = '',$intero='',$intere='', $fc = '', $fr = '') {

      global $db;

      $where = '';

      if ($id_esp != 0)

      {

      $where = " inter.id_especialidad=$id_esp";

      }

      if ($st != 0)

      {

      if ($where){

      $where.= " AND";

      }

      switch ($st)

      {

      case 1:

      $where .= " inter.login_consultado IS NOT NULL ";

      break;

      case 2:

      $where .= " inter.login_consultado IS NULL ";

      break;

      }

      }

      if (strlen($intero))

      {

      if ($where){

      $where.= " AND";

      }

      $where .= " inter.login_consultado IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intero%')";

      }

      if (strlen($intere))

      {

      if ($where){

      $where.= " AND";

      }

      $where .= " inter.login_consultante IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intere%')";

      }

      if (strlen($fc))

      {

      if ($where){

      $where.= " AND";

      }

      $where .= " (locate('$fc', inter.fecha_hora_consulta)!=0) ";

      }

      if (strlen($fr))

      {

      if ($where){

      $where.= " AND";

      }

      $where .= " (locate('$fr', inter.fecha_hora_respuesta)!=0) ";

      }

		/*$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.enfermedad_actual as enfermedad_actual, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" care_interconsulta_interconsulta AS inter".
			" INNER JOIN".
			" care_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" care_interconsulta_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)";

		if ($where){
			$q.= " WHERE ".$where;
		}

		// echo $q;

		$this->sql=$q;
		echo $this->sql;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}*/
      $salida = $db->GuiSelectBasicJoin(array('inter.id as id',' inter.establecimiento as establecimiento','inter.enfermedad_actual as enfermedad_actual', 'inter.respuesta as respuesta','inter.login_consultante as consultante','inter.login_consultado as consultado','esp.descripcion as especialidad','paciente.name_first as paciente'),array('1'=>1),'care_interconsulta_interconsulta AS inter, care_person AS paciente, care_interconsulta_especialidad AS esp'," paciente.pid=inter.id_paciente AND inter.id_especialidad=esp.id".$where);

      if($salida){ return $salida;

      } else { return false; }

      } 

        /**
	* Gets interconsultas based on an item list and login_consultante.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma. 
	* @param int ID number
	* @return mixed
	*/
	function getValueByConsultante($login_ico, $id_esp = '', $st = '', $intero = '', $fc = '', $fr = '') {
		global $db;

                $where = '';

                if ($id_esp != 0)
                {
                    $where = " AND inter.id_especialidad=$id_esp";
                }

                if ($st != 0)
                {
                    switch ($st)
                    {
                        case 1:
                            $where .= " AND inter.login_consultado IS NOT NULL ";
                            break;
                        case 2:
                            $where .= " AND inter.login_consultado IS NULL ";
                            break;
                    }
                }

                if (strlen($intero))
                {
                    $where .= " AND inter.login_consultado IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intero%')";
                }

                if (strlen($fc))
                {
	                    $where .= " AND (locate('$fc', inter.fecha_hora_consulta)!=0) ";
                }

                if (strlen($fr))
                {
	                    $where .= " AND (locate('$fr', inter.fecha_hora_respuesta)!=0) ";
                }

		/*$result=array();

		$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.motivo as motivo, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" $this->tb_interconsulta AS inter".
			" INNER JOIN".
			" $this->tb_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" $this->tb_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)".
		" WHERE ".
			" inter.login_consultante='$login_ico' $where";
		//echo $q;

		$this->sql=$q;
		echo $this->sql;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}*/


	     $salida = $db->GuiSelectBasicJoin(array('inter.id as id',' inter.establecimiento as establecimiento','inter.motivo as motivo', 'inter.respuesta as respuesta','inter.login_consultante as consultante','inter.login_consultado as consultado','esp.descripcion as especialidad','paciente.name_first as paciente'),array('inter.login_consultante'=>$login_ico),'care_interconsulta_interconsulta AS inter, care_person AS paciente, care_interconsulta_especialidad AS esp'," paciente.pid=inter.id_paciente AND inter.id_especialidad=esp.id".$where);

	      if($salida){ return $salida;

	      } else { return false; }
	}

/**
	* Gets all interconsulta information based on its ID number key.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllInfoObject($id) {
	    global $db;

          /*  $this->sql="SELECT 

i.*,

i.login_consultado AS ico_name,

p.apellido_1 as apellido_1, 

p.apellido_2 as apellido_2, 

p.name_1 as name_1, 

p.name_2 as name_2, 

p.sex as sex, 

p.etnia as etniaValue, 

esp.descripcion AS especialidad_descripcion, 

esp.id id_especialidad, 

u1.name AS ice_name

FROM care_interconsulta_interconsulta AS i

INNER JOIN  care_interconsulta_especialidad AS esp 

ON i.id_especialidad = esp.id

INNER JOIN care_users AS u1

ON (i.login_consultante = u1.login_id)

INNER JOIN care_interconsulta_datos_paciente AS p

ON (i.id_datos_paciente = p.id)

WHERE i.id=".$id; 

  echo $this->sql;

        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;	 
			} else { return false; }
		} else { return false; }*/

	    $salida = $db->GuiSelectBasicJoin(array('i.*',' i.login_consultado AS ico_name',' p.apellido_1 as apellido_1', 'p.apellido_2 as apellido_2',' p.name_1 as name_1',' p.name_2 as name_2',' p.sex as sex',' p.etnia as etniaValue',' esp.descripcion AS especialidad_descripcion',' esp.id id_especialidad',' u1.name AS ice_name'),array('i.id'=>$id),'care_interconsulta_interconsulta AS i, care_interconsulta_especialidad AS esp, care_users AS u1, care_interconsulta_datos_paciente AS p'," i.id_especialidad = esp.id AND i.login_consultante = u1.login_id AND i.id_datos_paciente = p.id");

	      if($salida){ return $salida;

	      } else { return false; }
	
}


/**
	* Same as getAllInfoObject() but returns a 2 dimensional array.
	*
	* The returned  data in the array have the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - citytown = name of the city or town
	*
	* @access public
	* @param int PID number
	* @return mixed array or boolean
	*/
	/*flag*/
	function getAllInfoArray($id='') {
	    global $db;
		 $x='';
		 $v='';
		 echo "hola";
		if(!$this->internResolveID($id)) return false;
		
	    $this->sql="SELECT i.*, esp.descripcion AS especialidad_descripcion, esp.id id_especialidad
					FROM $this->tb_interconsulta AS i
					LEFT JOIN  $this->tb_especialidad AS esp ON i.id_especialidad = esp.id
					WHERE i.id='$this->id' ";
		echo $this->sql;
        	if($this->result=$db->Execute($this->sql)) {

			if($this->result->RecordCount()) {
				return $this->row=$this->result->FetchRow();
			} else { return false; }
		} else { return false; }
	}



        function getAllPreguntasRespuestas($id)
        {
            global $db;

            /*$this->sql = "SELECT * from care_interconsulta_preguntas_respuestas WHERE id_interconsulta=$id ORDER BY id ASC";
            //echo $this->sql;
            if($this->result=$db->Execute($this->sql)) {
            	if($this->result->RecordCount()) {
					return $this->result;
				} else { return false; }
			} else { return false; }*/
			
        	$salida = $db->GuiSelect(array('*'),array('id_interconsulta'=>$id),'care_interconsulta_preguntas_respuestas','id ASC');
			if($salida) {
				return $salida;
			} else { return false; }

        }





	/**
	* Resolves the ID number to be used in the methods.
	* @access public
	* @param int ID number
	* @return boolean
	*/
	function internResolveID($id) {
	    if (empty($id)) {
		    if(empty($this->id)) {
			    return false;
			} else { return true; }
		} else {
		     $this->id=$id;
			return true;
		}
	}

        /**
	* Gets interconsultas based on an item list and login_consultado.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma. 
	* @param int ID number
	* @return mixed
	*/
	function getValueByConsultado($login_ico, $id_esp = '', $st = '', $intere = '', $fc = '', $fr = '') {
	    global $db;

                $where = '';

                if ($id_esp != 0)
                {
                    $where = " AND inter.id_especialidad=$id_esp";
                }

                if ($st != 0)
                {
                    switch ($st)
                    {
                        case 1:
                            $where .= " AND inter.login_consultado IS NOT NULL ";
                            break;
                        case 2:
                            $where .= " AND inter.login_consultado IS NULL ";
                            break;
                    }
                }

                if (strlen($intere))
                {
                    $where .= " AND inter.login_consultante IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intere%')";
                }

                if (strlen($fc))
                {
	                    $where .= " AND (locate('$fc', inter.fecha_hora_consulta)!=0) ";
                }

                if (strlen($fr))
                {
	                    $where .= " AND (locate('$fr', inter.fecha_hora_respuesta)!=0) ";
                }

		/*$result=array();
		$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.enfermedad_actual as enfermedad_actual, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" care_interconsulta_interconsulta AS inter".
			" INNER JOIN".
			" care_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" care_interconsulta_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)".
		" WHERE ".
			" inter.login_consultado='$login_ico' $where";
//               echo $q;
		$this->sql=$q;
		echo $this->sql;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}*/

	     $salida = $db->GuiSelectBasicJoin(array('inter.id as id',' inter.establecimiento as establecimiento', 'inter.enfermedad_actual as enfermedad_actual', 'inter.respuesta as respuesta','inter.login_consultante as consultante','inter.login_consultado as consultado','esp.descripcion as especialidad','paciente.name_first as paciente'),array('inter.login_consultado'=>$login_ico),'care_interconsulta_interconsulta AS inter, care_person AS paciente, care_interconsulta_especialidad AS esp'," paciente.pid=inter.id_paciente AND inter.id_especialidad=esp.id".$where);

	      if($salida){ return $salida;

	      } else { return false; }
	}
	/**
	* NO ESTA EN USO
        * Preloads the person registration data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function preloadPersonInfo($pid) {
	    global $db;

                if (empty($pid)) {
		    if(empty($this->id_paciente)) {
			    return false;
			} 
		} else {
		     $this->id_paciente=$pid;
			return true;
		}
		/*$this->sql="SELECT * FROM $this->tb_person WHERE pid=$this->id_paciente";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $this->person=$this->result->FetchRow();	
				 $this->is_preloaded=true; 
				 return true;
			} else { return false; }
		} else { return false; }
                */
           
            $salida=$db->GuiSelect(array('*'),array('pid'=>$this->id_paciente),$this->tb_person);
            if($salida) {

			$this->person=$salida;
			$this->is_preloaded=true;
			return true;

		} else { return false; }
	}
        /**
	* Preloads the person registration data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function preloadUserInfo($login) {
	    global $db;

	/*	$this->sql="SELECT name, matricula, clasificacion FROM $this->tb_users WHERE login_id='" . $login . "'";
//         echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $user=$this->result->FetchRow();
				 return $user;
			}
		} else { return false; }*/
            $salida=$db->GuiSelect(array('name','matricula','clasificacion'),array('login_id'=>$login),$this->tb_users);
            if($salida) {

			 $user=$salida[0];
			 return $user;

		} else { return false; }
	}
        /**
	* loads especialidades data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function loadEspecialidades() {
	    global $db;

	/*$this->sql="SELECT * FROM $this->tb_especialidad";
	var_dump($this->sql);
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
	var_dump($this->result);	
			while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }*/




           $salida=$db->GuiSelect(array('*'),array(NULL),$this->tb_especialidad);
            if($salida) {

			 $result=$salida;
			 return $result;

		} else { return false; }
	}
        /**
	* loads ethnic groups data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function loadEtnias() {
	    global $db;

		/*$this->sql="SELECT nr, name FROM care_type_ethnic_orig";
	var_dump($this->sql);
       if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			}
		} else { return false; }*/

        $salida=$db->GuiSelect(array('nr','name'),array(NULL),"care_type_ethnic_orig");
            if($salida) {

			 $result=$salida;
			 return $result;

		} else { return false; }

	}

	function loadEtnia($val) {
	    global $db;


//var_dump($val);
	/*	$this->sql="SELECT name FROM care_type_ethnic_orig WHERE nr=".$val;
var_dump($this->sql);
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				$temp = $this->result->FetchRow();
				 return $temp[0];
			}
		} else { return false; }*/


        $salida=$db->GuiSelect(array('name'),array('nr'=>$val),"care_type_ethnic_orig");
            if($salida) {

			 $result=$salida[0];
			 return $result;

		} else { return false; }

	}

	/**
	* get's
	*/
	function Establecimiento() {
        return $this->getValue('establecimiento');
	}
	
	function Justificacion() {
        return  $this->getValue('justificacion');
	}
	
	function ExamenFisico() {
        return  $this->getValue('examen_fisico');
	}

	function Peso() {
        return  $this->getValue('peso');
	}
	
	function Talla() {
        return  $this->getValue('talla');
	}
	
	function PresionArterial() {
        return  $this->getValue('presion_arterial');
	}
	
	function Temperatura() {
        return  $this->getValue('temp');
	}
	
	function FrecuenciaRespiratoria() {
        return  $this->getValue('respiratoria');
	}
	
	function Pulso() {
        return  $this->getValue('pulso');
	}
	
	function Consultante() {
        return  $this->getValue('login_consultante');
	}
	
	function Consultado() {
        return  $this->getValue('login_consultado');
	}
	
	function Paciente() {
        return  $this->getValue('id_paciente');
	}
	
	function Especialidad() {
        return  $this->getValue('id_especialidad');
	}

	function Evaluacion() {
        return  $this->getValue('evaluacion');
	}
	
	function IDx() {
        return  $this->getValue('IDx');
	}
	
	function PautaTerapeutica() {
        return  $this->getValue('pauta_terapeutica');
	}
	
	function DatosPaciente() {
        return  $this->getValue('id_datos_paciente');
	}

	/**
	* Returns especialidad name based on its "id" key.
	* @access public
	* @return mixed string or boolean
	*/
	function EspecialidadName($code_nr=''){
	    global $db;
		/*if(!$this->is_preloaded) $this->sql="SELECT descripcion FROM $this->tb_especialidad WHERE id=$code_nr";
            else $this->sql="SELECT descripcion FROM $this->tb_especialidad WHERE id=".$this->Especialidad();
			
		//echo $this->sql;exit;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $this->row=$this->result->FetchRow();	 
				 return $this->row['descripcion'];
			} else { return false; }
		} else { return false; }*/
		
		if(!$this->is_preloaded) $salida = $db->GuiSelect(array('descripcion'),array('id'=>$code_nr),$this->tb_especialidad);
			else $salida = $db->GuiSelect(array('descripcion'),array('id'=>$this->Especialidad()),$this->tb_especialidad);
		
		if($salida) {
			return $salida[0]['descripcion'];
		} else { return false; }
    }
	/**
	* Returns interconsulta items as listed in the <var>$basic_list</var> array based on pid key.
	*
	* The data is returned as associative array.
	* @access public
	* @param int PID number
	* @return mixed string or boolean
	*/
	function BasicDataArray($id){
        if(!$this->internResolveID($id)) return false;
		return $this->getValueByList($this->basic_list,$this->id);
	}
	/**
	* Adds a "View" note in the history field of the person's registration record.
	*
	* @access public
	* @param string Name of viewing person
	* @param int PID number
	* @return mixed string or boolean
	*/
	/*function setHistorySeen($encoder='',$pid=''){
	    global $db, $dbtype;
	    //$db->debug=true;
		if(empty($encoder)) return false;
		if(!$this->internResolvePID($pid)) return false;
        /*
		if($dbtype=='mysql')
			$this->sql="UPDATE $this->tb_person SET history= CONCAT(history,'\nView ".date('Y-m-d H:i:s')." = $encoder') WHERE pid=$this->pid";
		else
			$this->sql="UPDATE $this->tb_person SET history= history || '\nView ".date('Y-m-d H:i:s')." = $encoder' WHERE pid=$this->pid";
		//
        $this->sql="UPDATE $this->tb_person SET history=".$this->ConcatHistory("\nView ".date('Y-m-d H:i:s')." = $encoder")." WHERE pid=$this->pid";

		if($this->Transact($this->sql)) {return true;}
		   else  {echo $this->sql;return false;}
	}*/
	/**
	* Searches and returns a list of interconsultas based on search key.
	*
	* The returned adodb record object contains rows of arrays.
	* Each array contains the encounter data with the following index keys:
	* - especialidad
	* - establecimiento
	* - status (id_interconsultado null)
	* - interconsultante
        * - interconsultado
	* - fecha_hora_consulta
        * - fecha_hora_respuesta
	*
	* @access public
	* @param string Search keyword
	* @param string Sort by the item name, default = name_last (last/family name)
	*�@param string Sort direction, default = ASC (ascending)
	* @return mixed integer or boolean
	*/
	function Interconsultas($searchkey='',$order_item='id',$order_dir='ASC'){
	    global $db, $sql_LIKE;
		$searchkey=trim($searchkey);
		$searchkey=strtr($searchkey,'*?','%_');
		if(is_numeric($searchkey)) {
			$searchkey=(int) $searchkey;
			$this->is_nr=true;
			$order_item='pid';
			if(empty($order_dir)) $order_dir='DESC';
		} else {
			if(empty($order_item)) $order_item='id';
			if(empty($order_dir)) $order_dir='ASC';
			$this->is_nr=false;
		}
		
		return $this->SearchSelect($searchkey,'','',$order_item,$order_dir);
	}

        function loadGrupos()
        {
            global $db;
			
            /*$this->sql="SELECT DISTINCT nombre FROM $this->tb_grupo";
            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                                    while($temp=$this->result->FetchRow()){
                                            $result[]=$temp;
                                    }
                                    return $result;
                            }
                    } else { return false; }*/
                    
        	$salida = $db->GuiSelectDistinct(array('nombre'),array(''),$this->tb_grupo);
			if($salida) {
				return $salida;
			} else { return false; }
        }

        function saveUsuTriaje()
        {
            global $db, $_POST;
            extract($_POST);
            $asig = explode(":", $asigacum);

            //$this->sql = "SELECT login_id FROM $this->tb_grupo WHERE nombre='$nombre'";

            $temp = $db->GuiSelect(array('login_id'),array('nombre'=>$nombre),$this->tb_grupo);
            //if($this->result=$db->Execute($this->sql)) {
                //if($this->result->RecordCount()) {
                    //while($temp=$this->result->FetchRow()){
                if($temp){
                        for($i=0;$i<count($asig)-1;$i++)
                        {
                            if (strcmp($temp['login_id'], $asig[$i]))
                            {
                               	//$values .= "('$nombre', '" . $asig[$i] . "'),";
								$values []= array('nombre'=>$nombre, 'login_id'=>$asig[$i]);
                            }
                        }
                    //}

//                     return $result;
                }
                else
                {
                    for($i=0;$i<count($asig)-1;$i++)
                    {
                        //$values .= "('$nombre', '" . $asig[$i] . "'),";
							$values []= array('nombre'=>$nombre, 'login_id'=>$asig[$i]);
                    }
                }

                //$values=substr_replace($values,'',(strlen($values))-1);

                //$this->sql = "INSERT INTO $this->tb_grupo (nombre, login_id) VALUES $values";
		//echo $this->sql;

                foreach($values as $value)
                    {
                        
                        $x = $db->Transact("",$value,"Insert",$this->tb_espeusuario);

                        $return=$return && $x;
                        //var_dump($return);
                    }
                return $return;
            //}
            //else { return false; }
        }


	function getAllAsignables(){
		global $db;
		$result=array();

/*$q="SELECT inter.id as id, inter.motivo as motivo, inter.login_consultante as consultante, esp.descripcion as especialidad, esp.id id_especialidad 

FROM care_interconsulta_interconsulta AS inter
INNER JOIN care_interconsulta_especialidad AS esp
ON (inter.id_especialidad=esp.id) 
WHERE (inter.login_consultado IS NULL OR inter.login_consultado='') AND inter.estado=1;";
		$this->sql=$q;
		//echo $this->sql;
		if($this->result=$db->Execute($this->sql)) {
	//var_dump($this->result);
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}*/
	$salida = $db->GuiSelectBasicJoin(array('inter.id as id','inter.motivo as motivo','inter.login_consultante as consultante', 'esp.descripcion as especialidad','esp.id as id_especialidad'),array('inter.estado'=>1),'care_interconsulta_interconsulta AS inter, care_interconsulta_especialidad AS esp',"(inter.login_consultado IS NULL OR inter.login_consultado='')  AND inter.id_especialidad=esp.id");
			if($salida){ return $salida;
		} else { return false; }

	}

	/*function loadMedicosEspecialidad($id_especialidad, $ice_name) {
	    global $db;
	//echo "ID ESP:   ".$id_especialidad."  ID NAME:  ".$ice_name;
		$this->sql="SELECT usr.login_id as id, usr.name as name ".
			" FROM care_interconsulta_usuarioPerteneceEspecialidad rel ".
			" INNER JOIN care_users AS usr ".
			" ON (rel.login_id=usr.login_id)".
			" WHERE rel.id_especialidad=".$id_especialidad . " AND usr.name !=".$ice_name."";
		//var_dump($this->sql);
        if($this->result=$db->Execute($this->sql)) {

	//var_dump($this->result);
            if($this->result->RecordCount()) {
				 return $this->result;
			}
		} else { return false; }
	}*/
	function loadMedicosEspecialidad($id_especialidad, $ice_name) {
	    global $db;

	/*	$this->sql="SELECT usr.login_id as id, usr.name as name ".
			" FROM care_interconsulta_usuarioPerteneceEspecialidad rel ".
			" INNER JOIN care_users AS usr ".
			" ON (rel.login_id=usr.login_id)".
			" WHERE rel.id_especialidad=".$id_especialidad . " AND usr.name != '$ice_name'";

	//echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			}
		} else { return false; }*/


$salida = $db->GuiSelectBasicJoin(array('usr.login_id as id',' usr.name as name'),array('rel.id_especialidad'=>$id_especialidad), 'care_interconsulta_usuarioPerteneceEspecialidad rel, care_users AS usr',"usr.name !='".$ice_name."' AND rel.login_id=usr.login_id");
		if($salida){ return $salida;
		} else { return array(); }
	}




	/**
	* Gets interconsultas based on an item list and ID number.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma.
	* @param int ID number
	* @return mixed
	*/
	function getValueByList($list,$id='') {
	    global $db;
	
		if(empty($list)) return false;
		if(!$this->internResolveID($id)) return false;

		//$this->sql="SELECT $list FROM $this->tb_interconsulta, care_person WHERE id=$this->id AND id_paciente=pid";
			//echo $this->sql;
/*        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				$this->interconsulta=$this->result->FetchRow();	
				return $this->interconsulta;
			} else { return false; }
		} else { return false; }*/
		
		//Obteniendo el pid
		//$result = $db->GuiSelect(array('id_paciente'),array('id'=>$this->id),'care_interconsulta_interconsulta');
		//if($result){ $pid=$result[0]; } else { return false; }
		//$lista = explode(",",$list);

/*'id,id_paciente, id_especialidad, fecha_hora_consulta, establecimiento, motivo, justificacion, enfermedad_actual, examen_fisico, peso, talla, presion_arterial, temp, respiratoria, pulso, login_consultante, login_consultado, fecha_hora_respuesta, respuesta, diagnostico, tratamiento, observaciones, IDx, pauta_terapeutica, id_datos_paciente, comentarios, comentarios_resp, estado, motivo_cierre, clasificacion, interconsultas_previas,traslado,noadherencia,comentarios_clasif, name_first, name_2, name_middle, name_last, sex, ethnic_orig, create_id, id_especialidad'*/

		$salida = $db->GuiSelectBasicJoin(array('id','id_paciente',' id_especialidad',' fecha_hora_consulta',' establecimiento','motivo','justificacion','enfermedad_actual','examen_fisico','peso','talla','presion_arterial','temp','respiratoria','pulso','login_consultante','login_consultado','fecha_hora_respuesta','respuesta','diagnostico','tratamiento','observaciones','IDx','pauta_terapeutica','id_datos_paciente','comentarios','comentarios_resp','estado','motivo_cierre','clasificacion','interconsultas_previas','traslado','noadherencia','comentarios_clasif','name_first','name_2','name_middle','name_last','sex','ethnic_orig','create_id','id_especialidad'), array('id'=>$this->id),'care_interconsulta_interconsulta, care_person','id_paciente=pid');
		if($salida){ return $salida;
		} else { return false; }
	}





	function asignarMedico($id,$login_id){
		global $db;

	    //$this->sql="UPDATE $this->tb_interconsulta SET login_consultado='".$login_id."' WHERE id=".$id;

		return $db->Transact(array('id'=>$id),array('login_consultado'=>$login_id),'Update',$this->tb_interconsulta);

	}

        function saveEspeUsuario()
        {
            global $db, $_POST;
            extract($_POST);
            $return=TRUE;
            $values=array();
            $asig = explode(":", $asigacum);
            //var_dump($asigacum);
            //$this->sql = "SELECT id_especialidad FROM $this->tb_espeusuario WHERE login_id='$login_id'";

            $temp = $db->GuiSelect(array('id_especialidad'),array('login_id'=>$login_id),$this->tb_espeusuario);
            //if($this->result=$db->Execute($this->sql)) {
                //if($this->result->RecordCount()) {
                    //while($temp=$this->result->FetchRow()){
            	if($temp){//var_dump($asigacum);
                        for($i=0;$i<count($asig)-1;$i++)
                        {
                            if (strcmp($temp['id_especialidad'], $asig[$i]))
                            {
                                $values []= array('login_id'=>$login_id, 'id_especialidad'=>$asig[$i]);
                            }
                        }
                    //}
//                     return $result;
                }
                else
                {
                    for($i=0;$i<count($asig)-1;$i++)
                    {
                        $values []= array('login_id'=>$login_id, 'id_especialidad'=>$asig[$i]);
                    }
                }

                //$values=substr_replace($values,'',(strlen($values))-1);

                //$this->sql = "INSERT INTO $this->tb_espeusuario (login_id, id_especialidad) VALUES $values";
                // echo $this->sql;
                
                //var_dump($values);
                foreach($values as $value)
                    {
                        
                        $x = $db->Transact("",$value,"Insert",$this->tb_espeusuario);

                        $return=$return && $x;
                        //var_dump($return);
                    }
                    //echo ("retorno <br>");
                    //var_dump($return);
                return $return;
            //}
            //else { return false; }
        }

        function insertarBitacora($msj)
        {
            global $db;

            //$this->sql = "INSERT INTO care_interconsulta_bitacora (id_interconsulta, mensaje, fecha) VALUES ($this->id, '$msj', '" . date("Y-m-d") . "')";

            //echo $this->sql;

			//var_dump($msj);
            return $db->Transact(NULL,array('id_interconsulta'=>$this->id, 'mensaje'=>$msj, 'fecha'=>date("Y-m-d")),"Insert","care_interconsulta_bitacora");
        }

	function cerrar($motivo, $traslado, $noadherencia, $clasif, $comentarios_clasif)
        {
            global $db;
	
            /*$this->sql = "UPDATE care_interconsulta_interconsulta SET estado = '2', motivo_cierre = '$motivo', traslado = '$traslado', noadherencia = '$noadherencia', clasificacion = '$clasif', comentarios_clasif = '$comentarios_clasif' WHERE id = '" . $this->id . "'";*/

             //echo $this->sql;

            //return $this->Transact();

	 $db->Transact(array('id'=>$this->id),array('estado'=>2, 'motivo_cierre'=>$motivo, 'traslado'=>$traslado,'noadherencia'=>$noadherencia,'clasificacion'=>$clasif,'comentarios_clasif'=>$comentarios_clasif), "Update","care_interconsulta_interconsulta");
        }

        function getBitacora($id_ic)
        {
            global $db;

            /*$this->sql = "SELECT DISTINCT id_interconsulta, mensaje, fecha FROM $this->tb_bitacora WHERE id_interconsulta=$id_ic";

            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow()){
                        $result[]=$temp;
                    }
                    return $result;
                }
            }
            else {
                return false;
            }*/
            
			$salida = $db->GuiSelectDistinct(array('id_interconsulta','mensaje','fecha'),array('id_interconsulta'=>$id_ic),$this->tb_bitacora);
			if($salida) {
				return $salida;
			} else { return false; }
        }

	function guardarAdjunto($fileInput, $resp=''){
		global $db;


		if($fileInput!=''){
			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 
			
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
	

			$value= array('name'=>$fileInput, 'size'=>$size,'content'=>$imgData,'id_interconsulta'=>$this->id);


			$db->Transact("",$value,"Insert",$this->tb_adjunto.$resp);


			/*$this->sql = "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta) VALUES ('$fileInput', $size, '$imgData',$this->id)";
	
			$this->Transact();*/
		}

	}

	function guardarAdjuntoPregResp($fileInput, $idPreg, $resp = ''){
		global $db;

		system("logger -t sinapsis GAPR $fileInput $resp");

		if($fileInput!=''){

			system("logger -t sinapsis opening " . $fileInput);

			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 

			system("logger -t sinapsis closing $resp " . $fileInput);
			/*Esto es para el log de operaciones*/
			system("logger -t sinapsis " . "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta, id_preg) VALUES ('$fileInput', $size, '$imgData',$this->id, $idPreg)");
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
			
			

	
			/*$this->sql = "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta, id_preg) VALUES ('$fileInput', $size, '$imgData',$this->id, $idPreg)";*/
			/*Esto es para el log de operaciones*/
			system("logger -t sinapsis " . "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta, id_preg) VALUES ('$fileInput', $size, '$imgData',$this->id, $idPreg)");

			$value= array('name'=>$fileInput, 'size'=>$size,'content'=>$imgData,'id_interconsulta'=>$this->id,'id_preg'=>$idPreg);


			$db->Transact("",$value,"Insert",$this->tb_adjunto.$resp);

			//$this->Transact();
		}

	}

	function seleccionarNombreAdjuntos($id, $resp=''){
		global $db;

		/*$this->sql = "SELECT name FROM $this->tb_adjunto" . $resp . " WHERE id_interconsulta=".$id . " AND id_preg = 0";

		//echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}
		else {
		return false;
		}*/
		//var_dump( $this->tb_adjunto);
        $salida=$db->GuiSelect(array('name'),array('id_interconsulta'=>$id, 'id_preg'=>'0'),"$this->tb_adjunto$resp");
        if($salida) {
			//var_dump($salida);
			 $result=$salida;
			 return $result;

		} else { return array(''); }

	}

	function seleccionarNombreAdjuntosPregResp($id, $idPreg, $resp=''){
		global $db;

		/*$this->sql = "SELECT name FROM $this->tb_adjunto" . $resp . " WHERE id_interconsulta=".$id . " AND id_preg = " . $idPreg;

// 		echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}
		else {
		return false;
		}*/

        $salida=$db->GuiSelect(array('name'),array('id_interconsulta'=>$id, 'id_preg'=>$idPreg),"$this->tb_adjunto$resp");
            if($salida) {

			 $result=$salida;
			 return $result;

		} else { return array(''); }

	}


	function seleccionarAdjuntos($id,$name, $resp=''){
		global $db;

		/*$this->sql = "SELECT * FROM $this->tb_adjunto$resp WHERE id_interconsulta=".$id." AND name='".$name."'";

// 		echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}Línea 435  , Archivo: include/care_api_classes/class_interconsulta.php
 
		}
		else {
		return false;
		}*/
          $salida=$db->GuiSelect(array('*'),array('id_interconsulta'=>$id, 'name'=>$name),$this->tb_adjunto);
            if($salida) {

			 $result=$salida;
			 return $result;

		} else { return false; }

	}

	function getMail($medico){
		global $db;
		
		//$this->sql = "SELECT mail FROM $this->tb_users WHERE login_id=$medico";
		/*if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }*/
		$salida = $db->GuiSelect(array('mail'),array('login_id'=>$medico),$this->tb_users);
		if($salida){ return $salida;
		} else { return false; }
	}
	
	function getAllMailTriaje(){
		global $db;
	
		//$this->sql="SELECT mail FROM $this->tb_users where login_id IN (SELECT DISTINCT login_id FROM $this->tb_grupo)";
		/*$this->sql="SELECT mail FROM $this->tb_users WHERE permission='_a_2_intertriajewrite ";
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }*/
		
		$salida = $db->GuiSelect(array('mail'),array('permission'=>'_a_2_intertriajewrite'),$this->tb_users);
		if($salida) {
			return $salida;
		} else { return false; }

	}
}



?>
